<script setup>
	import {
		ref,
		onMounted,
		onBeforeUnmount
	} from "vue"
	import {
		formatTime,
	} from "/utils/index.js"
	import {
		gengXinBanBenApi
	} from "/api/request.js"
	const audio = ref(null)
	const startSlider = ref(0)
	const endSlider = ref(0)
	const version = ref({})
	onMounted(async () => {
		audio.value = uni.createInnerAudioContext()
		audio.value.onCanplay(() => {
			if (startSlider.value) {
				audio.value.seek(startSlider.value)
			}
			uni.hideLoading()
		});
		audio.value.onTimeUpdate(() => {
			uni.$emit('time', audio.value.currentTime)
			if (endSlider.value > 0 && audio.value.currentTime > endSlider.value) {
				console.log(endSlider.value);
				audio.value.seek(0)
				audio.value.pause()
			}
		});
		audio.value.onPlay(() => {});
		audio.value.onPause(() => {});
		audio.value.onEnded(() => {
			uni.$emit('playend')
		})
		let selfVersionCode;
		plus.runtime.getProperty(plus.runtime.appid, async function(wgtinfo) {
			selfVersionCode = wgtinfo.version;
		});
		const compareVersions = (v1, v2) => {
			const v1Parts = v1.split('.').map(Number);
			const v2Parts = v2.split('.').map(Number);

			for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
				const v1Part = v1Parts[i] || 0;
				const v2Part = v2Parts[i] || 0;
				if (v1Part > v2Part) return 1;
				if (v1Part < v2Part) return -1;
			}
			return 0;
		};
		let res = await gengXinBanBenApi({
			type: 1
		});
		version.value = res.data;
		if (compareVersions(selfVersionCode, (version.value.android_version || '1.0.0')) >= 0) {
			return;
		}
		let globalLoadingShown = false;
		let loadingInstance = null;
		const showGlobalLoading = (message) => {
			if (!globalLoadingShown) {
				globalLoadingShown = true;
				loadingInstance = plus.nativeUI.showWaiting(message);
			}
		};
		const updateGlobalLoading = (percent) => {
			if (loadingInstance) {
				loadingInstance.setTitle(`下载中... ${percent}%`);
			}
		};
		const hideGlobalLoading = () => {
			if (globalLoadingShown) {
				globalLoadingShown = false;
				if (loadingInstance) {
					plus.nativeUI.closeWaiting();
					loadingInstance = null;
				}
			}
		};
		showGlobalLoading('下载更新文件...');

		const dtask = plus.downloader.createDownload(
			version.value.android_bag, {
				method: 'GET', // 可选：设置为 'POST' 进行 POST 请求
				timeout: 30 // 可选：设置超时时间
			},
			(d, status) => {
				hideGlobalLoading();

				if (status === 200) {
					// 下载成功
					const fileSaveUrl = plus.io.convertLocalFileSystemURL(d
						.filename); // 获取保存的文件路径
					console.log('下载成功:', fileSaveUrl);

					plus.nativeUI.showWaiting('安装中...');
					plus.runtime.install(
						fileSaveUrl, {
							force: false
						},
						() => {
							plus.nativeUI.closeWaiting();
							plus.nativeUI.alert('更新成功', () => {
								plus.runtime.restart();
							});
						},
						(e) => {
							plus.nativeUI.closeWaiting();
							plus.nativeUI.alert(`安装失败: ${e.message}`);
							if (e.code === 10) {
								uni.removeSavedFile({
									filePath: d.filename
								});
							}
						}
					);
				} else {
					// 下载失败
					plus.nativeUI.alert('下载失败，请重试！');
				}
			}
		);

		// 监听下载进度
		dtask.addEventListener('statechanged', (download, status) => {
			if (status === 404) {
				uni.showToast({
					title: '网络异常正在重试',
					icon: 'none'
				});
			}
			if (download.state === 3) {
				// 下载中
				const percent = Math.floor((download.downloadedSize / download
					.totalSize) * 100); // 计算下载进度
				updateGlobalLoading(percent);

				if (percent < 0.1) {
					// 防止进度显示为 0
					updateGlobalLoading(1);
				}
			}
		});

		// 开始下载
		dtask.start();
	})
	onBeforeUnmount(() => {
		audio.value.pause();
		audio.value.destroy();
		audio.value = null;
		uni.$off('playAudio')
		uni.$off('pause')
		uni.$off('play')
		uni.$off('changeTabbarBg')
	})
	uni.$on('playAudio', (audioSrc, play = true, start = 0, end = 0) => {
		console.log(audioSrc);
		audio.value.pause();
		startSlider.value = Number(start) / 1000
		endSlider.value = Number(end) / 1000
		if (audio.value.src == audioSrc) {
			audio.value.seek(startSlider.value)
		} else {
			audio.value.src = audioSrc
		}
		if (play) audio.value.play()
	})
	// 暂停
	uni.$on('pause', () => {
		audio.value.pause()
	})
	// 播放
	uni.$on('play', () => {
		audio.value.play()
	})
</script>


<script>
	export default {
		onLaunch: function() {
			// 状态栏高度
			uni.getSystemInfo({
				success: (res) => {
					let rpxs = (750 * 1) / res.screenWidth;
					let gaodu = res.screenHeight * rpxs;
					let kuandu = res.screenWidth * rpxs;
					let dingbu = res.statusBarHeight * rpxs;
					const platform = {
						rpxs: rpxs,
						gaodu: gaodu,
						kuandu: kuandu,
						dingbu: dingbu,
					}
					uni.setStorageSync('platform', platform);
				}
			});

		},
		onShow: function() {},
		onHide: function() {
			console.log('App Hide')
		}
	}
</script>

<style>
	@import url('/static/css/global.less');
	@import url('/static/css/reset.less');

	@font-face {
		font-family: 'yinbiao';
		src: url('/static/yinbiao.ttf');
	}

	@font-face {
		font-family: 'xinyinbiao';
		src: url('/static/123.ttf');
	}

	@font-face {
		font-family: 'yingwen';
		src: url('/static/yingwen.ttf');
	}

	.yinbiao {
		font-family: 'xinyinbiao';
	}

	.yingwen {
		font-family: 'yingwen';
	}
</style>